package files

import (
	"clouds.lgb24kcs.cn/controllers/files/request"
	"clouds.lgb24kcs.cn/errorx"
	"clouds.lgb24kcs.cn/global"
	"clouds.lgb24kcs.cn/models"
	"clouds.lgb24kcs.cn/utils"
	"clouds.lgb24kcs.cn/utils/history"
	"clouds.lgb24kcs.cn/utils/oss"
	"github.com/gin-gonic/gin"
)

type ObjectDelet struct {
}

var ObjectDeleteAPI ObjectDelet

func (d *ObjectDelet) Delete(c *gin.Context, req request.ObjectDel, userId int64) {
	// 删除oss存储对象数据
	buckerInfo := models.Storage{}
	api := oss.OSS{}

	tx := global.APP.DB.Where("bucketname=?  and userid=?", req.BucketName, userId).First(&buckerInfo)
	if tx.Error != nil {
		global.APP.Log.Error(tx.Error.Error())
		utils.Fail(c, errorx.ObjectDel, tx.Error.Error())
	} else if tx.RowsAffected == 0 {
		global.APP.Log.Error("没有该数据")
		utils.Fail(c, errorx.ObjectDel, "没有该数据")

	} else {
		client := api.NewClient(buckerInfo.Accesskey, buckerInfo.Secretkey, buckerInfo.Zone)
		if err := api.DelObject(client, req.BucketName, req.CatalogueName+"/"+req.ObjectName); err != nil {
			global.APP.Log.Error(err.Error())
			utils.Fail(c, errorx.ObjectDel, err.Error())
		} else {
			tx := global.APP.DB.Where("bucketname=? and root_dir=? and  user_id=? and filename=?", req.BucketName, req.CatalogueName, userId, req.ObjectName).Delete(&models.Files{})
			if tx.Error != nil {
				global.APP.Log.Error(tx.Error.Error())
				utils.Fail(c, errorx.ObjectDel, tx.Error.Error())
			} else {
				if err := history.HistoryCreate(userId, c.Request.Method, c.Request.URL.String(), c.Request.Host); err != nil {
					utils.Fail(c, errorx.ObjectSearch, err.Error())
				} else {
					utils.Success(c, 0, "删除成功")
				}

			}
		}
		//utils.Success(c, 0, "删除成功")
	}

}
